package com.tiger.mgr 
{
	import com.tiger.utils.VectorUtils;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	/**
	 * 全局唯一的ENTER_FRAME的监听处
	 * @author wmTiger
	 */
	public class TickMgr 
	{
		private static var mInstance:TickMgr;
		
		private var mFunVector:Vector.<Function>;// EnterFrame的挂载函数集合
		private var mTimerFunVector:Vector.<Function>;// Timer的挂载函数集合
		private var mStage:Stage;
		private var mTimer:Timer;
		private var mEFCount:int = 0;// EnterFrame的当前计数
		private var mTimerCount:int = 0;// Timer的当前计数(秒为单位)
		
		public function TickMgr() 
		{
			mFunVector = new Vector.<Function>();
			mTimerFunVector = new Vector.<Function>();
		}
		
		static public function get instance():TickMgr 
		{
			if (mInstance == null) 
			{
				mInstance = new TickMgr();
			}
			return mInstance;
		}
		
		public function init(stage:Stage = null):void
		{
			if (stage != null) 
			{
				mStage = stage;
				mStage.addEventListener(Event.ENTER_FRAME, onLoop);// 全局唯一的EnterFrame
				mTimer = new Timer(1000);
				mTimer.addEventListener(TimerEvent.TIMER, onTimer);// 全局唯一的Timer
				mTimer.start();
			}
		}
		
		private function onTimer(e:TimerEvent):void 
		{
			var l:int = mTimerFunVector.length;
			for (var i:int = 0; i < l; i++) 
			{
				mTimerFunVector[i].call(null, mTimerCount);
			}
			mTimerCount++;
		}
		
		private function onLoop(e:Event):void
		{
			var l:int = mFunVector.length;
			for (var i:int = 0; i < l; i++) 
			{
				mFunVector[i].call(null, mEFCount);
			}
			mEFCount++;
		}
		
		/**
		 * 插入TIMER中运行的函数，时间间隔为1秒
		 * @param	func
		 */
		public function addTimerListener(func:Function):void
		{
			mTimerFunVector.push(func);
		}
		/**
		 * 删除插入TIMER中运行的函数
		 * @param	func
		 */
		public function removeTimerListener(func:Function):void
		{
			VectorUtils.removeValueFromFuncVector(mTimerFunVector, func);
		}
		
		/**
		 * 插入ENTER_FRAME中运行的函数
		 * @param	func
		 */
		public function addListener(func:Function):void
		{
			if (!VectorUtils.contains(mFunVector, func)) 
			{
				mFunVector.push(func);
			}
		}
		/**
		 * 删除插入ENTER_FRAME中运行的函数
		 * @param	func
		 */
		public function removeListener(func:Function):void
		{
			VectorUtils.removeValueFromFuncVector(mFunVector, func);
		}
		
	}

}